/*
* ===================================================
*
*       Filename:  block.c
*
*
*        Created:  10/13/2011 03:07:30 PM
*       Revision:  none
*       Compiler:  gcc
*
*         Author:  durand_y, <durand.yoan@gmail.com>
*
* ===================================================
*/
#include "malloc.h"

int             fit_in_page(size_t          size,
                            s_block         *block,
                            s_map           *map_list)
{
    int     nb_page = 0;
    void    *ptr = NULL;
    void    *ptr2 = NULL;
    char    *s = NULL;
    long    page = 0;

    page = sysconf(_SC_PAGE_SIZE);
    ptr = block->end;
    s = ptr;
    s += block->size;
    s += (long unsigned int)s % sizeof (size_t) + sizeof (s_block) + size;
    ptr2 = map_list;
    ptr = s;
    if (((map_list->block->size) % page) != 0 )
        nb_page = ((map_list->block->size / page) + 1);
    else
        nb_page = ((map_list->block->size) / page);
    s = ptr2;
    s = s + (nb_page * page);
    ptr2 = s;
    if (ptr > ptr2)
        return (0);
    else
        return (1);
}

void    *find_next(s_block  *b,
                   s_map    *map,
                   size_t   size)
{
    while (map != NULL)
    {
        while ((b->next != NULL) && (b != NULL))
        {
            if ((b->state == FREE) && (b->size >= size))
            {
                split(b, size);
                b->size = size;
                b->state = NON_FREE;
                return (b->end);
            }
            b = b->next;
        }
        if (fit_in_page(size, b, map) == 0)
        {
            if ((map = map->next_map) != NULL)
                b = map->block;
        }
        else
             return (new_block(b, size));
    }
    return (NULL);
}

void    *new_block(s_block  *b,
                   size_t   size)
{
    void    *ptr = NULL;
    char    *s = NULL;

    ptr = b->end;
    s = ptr;
    s += b->size;
    s += (long unsigned int)s % sizeof (size_t);
    ptr = s;
    b->next = ptr;
    b = b->next;
    b->size = size;
    b->next = NULL;
    b->state = NON_FREE;
    ptr = b;
    s = ptr;
    s = s + sizeof (s_block);
    ptr = s;
    b->end = ptr;
    return (b->end);
}
